package com.xjc.business.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjc.business.entity.domain.AllStudentRegsiterRelations;
import com.xjc.business.entity.domain.Students;
import com.xjc.business.entity.domain.WxAuthenticatedIdentityApplys;
import com.xjc.business.entity.domain.WxUser;
import com.xjc.business.entity.po.stu.AuthPo;
import com.xjc.business.entity.po.stu.MatchFacePo;
import com.xjc.business.entity.vo.stu.AuthVo;
import com.xjc.business.service.*;
import com.xjc.business.mapper.WxAuthenticatedIdentityApplysMapper;
import com.xjc.system.constants.MyConstants;
import com.xjc.system.result.Result;
import com.xjc.system.utils.BcryptUtil;
import com.xjc.system.utils.FaceCardMatchUtils;
import com.xjc.system.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
* @author root
* @description 针对表【wx_authenticated_identity_applys(学生身份认证表)】的数据库操作Service实现
* @createDate 2025-01-25 10:24:33
*/
@Service
public class WxAuthenticatedIdentityApplysServiceImpl extends ServiceImpl<WxAuthenticatedIdentityApplysMapper, WxAuthenticatedIdentityApplys>
    implements WxAuthenticatedIdentityApplysService {

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Autowired
    @Lazy
    StudentsService studentsService;

    @Autowired
    @Lazy
    AllStudentRegsiterRelationsService allStudentRegsiterRelationsService;

    @Autowired
    @Lazy
    WxUserService wxUserService;


    @Autowired
    @Lazy
    SchoolsService schoolsService;

    @Autowired
    @Lazy
    CollegesService collegesService;

    @Autowired
    @Lazy
    MajorsService majorsService;

    @Autowired
    @Lazy
    ClazzsService clazzsService;

    /**
     * 匹配人脸和身份证号
     *
     * @param matchFacePo 数据
     * @return 反馈
     */
    @Override
    public Result<String> matchFaceAndIdCard(MatchFacePo matchFacePo) {
        Integer matchResultCode = FaceCardMatchUtils.match(matchFacePo.getIdCard(), matchFacePo.getName(), matchFacePo.getImage());
        if(matchResultCode == 1001){
            String token = TokenUtils.generateToken(matchFacePo.getIdCard());

            matchFacePo.setImage("");
            redisTemplate.opsForValue().set(MyConstants.PREFIX_TOKEN+matchFacePo.getIdCard(), JSONArray.toJSONString(matchFacePo),60, TimeUnit.SECONDS);

            return Result.okWithData(token);
        } else if (matchResultCode == 1002 || matchResultCode == 1003) {
            return Result.ok("非本人操作");
        } else if (matchResultCode == 1004) {
            return Result.ok("身份信息错误");
        }else if (matchResultCode == 400) {
            return Result.ok("姓名或者身份证无效");
        }else {
            return Result.ok("匹配失败,稍后再试");
        }
    }

    /**
     * 继续认证
     *
     * @param authPo 数据
     * @return 反馈
     */
    @Override
    @Transactional
    public Result<String> completeAuthentication(AuthPo authPo) {

        String authToken = authPo.getAuthToken();

        MatchFacePo matchFacePo = JSONArray.parseObject((String) redisTemplate.opsForValue().get(MyConstants.PREFIX_TOKEN + TokenUtils.parseToken(authToken).getSubject()), MatchFacePo.class);

        if (matchFacePo == null){
            return Result.ok("已过期，请重新认证");
        }

        if(!(matchFacePo.getIdCard().equals(authPo.getCardId())) ||!( matchFacePo.getName().equals(authPo.getName()))){
            return Result.ok("不一致，请重新认证");
        }

        LambdaQueryWrapper<Students> studentsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        studentsLambdaQueryWrapper.eq(Students::getSno,authPo.getSno());
        studentsLambdaQueryWrapper.eq(Students::getName,authPo.getName());
        studentsLambdaQueryWrapper.eq(Students::getCardId,authPo.getCardId());
        studentsLambdaQueryWrapper.eq(Students::getPhone,authPo.getPhone());
        studentsLambdaQueryWrapper.eq(Students::getEmail,authPo.getEmail());

        Students studentFromDB = studentsService.getOne(studentsLambdaQueryWrapper);

        if (studentFromDB == null){
            return Result.ok("认证信息不存在");
        }

        LambdaQueryWrapper<AllStudentRegsiterRelations> allStudentRegsiterRelationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        allStudentRegsiterRelationsLambdaQueryWrapper.eq(AllStudentRegsiterRelations::getStuId,studentFromDB.getId());
        allStudentRegsiterRelationsLambdaQueryWrapper.eq(AllStudentRegsiterRelations::getSchId,authPo.currentSchoolId);
        allStudentRegsiterRelationsLambdaQueryWrapper.eq(AllStudentRegsiterRelations::getColId,authPo.currentCollegeId);
        allStudentRegsiterRelationsLambdaQueryWrapper.eq(AllStudentRegsiterRelations::getMajId,authPo.currentMajorId);
        allStudentRegsiterRelationsLambdaQueryWrapper.eq(AllStudentRegsiterRelations::getClazzId,authPo.currentClassId);
        AllStudentRegsiterRelations allStudentRegsiterRelationsServiceOne = allStudentRegsiterRelationsService.getOne(allStudentRegsiterRelationsLambdaQueryWrapper);
        if (allStudentRegsiterRelationsServiceOne == null){
            return Result.ok("认证信息不存在");
        }

        WxUser wxUser = wxUserService.getById(matchFacePo.getWxId());
        if (wxUser == null){
            return Result.ok("操作不合法");
        }

        wxUser.setStuId(studentFromDB.getId());
        wxUser.setStatus(1);

        wxUserService.updateById(wxUser);

        WxAuthenticatedIdentityApplys wxAuthenticatedIdentityApplys = new WxAuthenticatedIdentityApplys();
        wxAuthenticatedIdentityApplys.setWxId(wxUser.getId());
        wxAuthenticatedIdentityApplys.setSno(authPo.getSno());
        wxAuthenticatedIdentityApplys.setCardId(authPo.getCardId());
        wxAuthenticatedIdentityApplys.setName(authPo.getName());
        wxAuthenticatedIdentityApplys.setSchCode(authPo.currentSchoolId);
        wxAuthenticatedIdentityApplys.setColCode(authPo.currentCollegeId);
        wxAuthenticatedIdentityApplys.setMajCode(authPo.currentMajorId);
        wxAuthenticatedIdentityApplys.setClassCode(authPo.currentClassId);
        wxAuthenticatedIdentityApplys.setPhone(authPo.getPhone());
        wxAuthenticatedIdentityApplys.setEmail(authPo.getEmail());
        wxAuthenticatedIdentityApplys.setStatus(1);
        wxAuthenticatedIdentityApplys.setCreateTime(new Date());
        wxAuthenticatedIdentityApplys.setUpdateTime(new Date());

        save(wxAuthenticatedIdentityApplys);
        return Result.okWithData("认证成功");
    }

    /**
     * 获取认证信息
     * @param id 微信id
     * @return 反馈
     */
    @Override
    public Result<AuthVo> getAuthInfo(Integer id) {
        WxUser wxUser = wxUserService.getById(id);
        Integer stuId = wxUser.getStuId();
        Students students = studentsService.getById(stuId);

        AuthVo authVo = new AuthVo();
        authVo.setSno(students.getSno());
        authVo.setName(students.getName());
        authVo.setCardId(students.getCardId());
        authVo.setPhone(students.getPhone());
        authVo.setEmail(students.getEmail());

        LambdaQueryWrapper<AllStudentRegsiterRelations> allStudentRegsiterRelationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        allStudentRegsiterRelationsLambdaQueryWrapper.eq(AllStudentRegsiterRelations::getStuId,stuId);
        AllStudentRegsiterRelations allStudentRegsiterRelations = allStudentRegsiterRelationsService.getOne(allStudentRegsiterRelationsLambdaQueryWrapper);
        authVo.setSchoolName(schoolsService.getById(allStudentRegsiterRelations.getSchId()).getSchoolName());
        authVo.setCollegeName(collegesService.getById(allStudentRegsiterRelations.getColId()).getName());
        authVo.setMajorName(majorsService.getById(allStudentRegsiterRelations.getMajId()).getName());
        authVo.setClassName(clazzsService.getById(allStudentRegsiterRelations.getClazzId()).getNum()+"班");

        return Result.okWithData(authVo);
    }
}




